package com.ruoyi.common.core.utils.sms;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 发送短信
 */
public class AliyunSendSMS {

    private static final Logger logger = LoggerFactory.getLogger(AliyunSendSMS.class);

    private static final String accessKeyId = "LTAI5tNQksFxgB1b6FCrxRbx";
    private static final String accessKeySecret = "duBSXLUOKF9YaXq2lP6Yt9FEX1OlOl";
    private static final String signName = "藻上好";
    private static final String templateCode = "SMS_236375309";

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信
     * @param mobile  手机号
     * @param code    验证码
     * @return
     */
    public static boolean sendSms(String mobile,String code){
        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            client = AliyunSendSMS.createClient(accessKeyId, accessKeySecret);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(signName)
                    .setPhoneNumbers(mobile)
                    .setTemplateCode(templateCode)
                    .setTemplateParam("{\"code\":\""+code+"\"}");

            SendSmsResponse sendSmsResponse =  client.sendSms(sendSmsRequest);
            if (sendSmsResponse != null && sendSmsResponse.body.code.equals("OK")){
                return true;
            }else {
                logger.error("短信接口报错 code：",sendSmsResponse.getBody().code.toString() );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


}
